//
//  AppExtension.swift
//  NetworkTest
//
//  Created by SuPeiSen on 2020/11/23.
//

import Foundation
import Moya
import HandyJSON

// MARK: String Extension

extension String{
    
    public var utf8Encoded: Data {
        get {
            return self.data(using: .utf8)!
        }
    }
}

// MARK: Response Extension

extension Response {
    /// 转model
    /// - parameters
    /// - model:  Model.Self 对象本身
    func toJsonModel<T: HandyJSON>(model: T.Type) -> T?{
        if let jsonStr = String(data: self.data, encoding: .utf8) {
            if let object = T.deserialize(from: jsonStr){
                return object
            }
        }
        return nil
    }
}

// MARK: Response Dictionary

extension Dictionary{
    /// 字典(Dictionary)转字符串json
    func toJsonString() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
            return nil
        }
        guard let str = String(data: data, encoding: .utf8) else {
            return nil
        }
        return str
    }
}

// MARK: Response UIImageView
extension UIImageView {
    func setFuzz(value: CGFloat){
        if let image = self.image {
            let context = CIContext(options: nil)
            let inputImage = CIImage(image: image)
            let filter = CIFilter(name: "CIGaussianBlur")!
            filter.setValue(inputImage, forKey: kCIInputImageKey)
            filter.setValue(value, forKey: kCIInputRadiusKey)
            let outputImage = filter.outputImage!
            let cgImage = context.createCGImage(outputImage, from: CGRect(origin: .zero, size: self.frame.size))
            self.image = UIImage(cgImage: cgImage!)
            context.clearCaches()
        }
    }
}

